package com.zzjson.common.utils;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public class PageQueryUtils {

    public static <T> void splitExecute(List<T> originList, Consumer<List<T>> consumer, int pageSize) {
        splitJoinExecute(originList, (arg) -> {
            consumer.accept(arg);
            return null;
        }, pageSize);
    }

    /**
     * list拆分执行然后在合并
     * @param originList
     * @param function
     * @param pageSize
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> List<R> splitJoinExecute(List<T> originList, Function<List<T>, List<R>> function,
                                                  int pageSize) {
        List<R> result = new ArrayList<>();
        for (int i = 0; i * pageSize < originList.size(); i++) {

            int formIndex = i * pageSize;
            int toIndex = formIndex + pageSize;

            if (originList.size() >= toIndex) {
                List<R> subResult = function.apply(originList.subList(formIndex, toIndex));
                if (subResult == null) {
                    continue;
                }
                result.addAll(subResult);
            } else {
                List<T> subList = originList.subList(formIndex, originList.size());
                if (CollectionUtils.isEmpty(subList)) {
                    break;
                }

                List<R> subResult = function.apply(subList);
                if (subResult == null) {
                    break;
                }
                result.addAll(subResult);
                break;
            }
        }
        return result;
    }
}